package com.magicsoft.share.ui.exchange;


import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.magicsoft.share.R;
import com.magicsoft.share.adapter.exchange.ShopCartAdapter;
import com.magicsoft.share.base.BaseFragment;
import com.magicsoft.share.bean.exchange.CheckStockValid;
import com.magicsoft.share.bean.exchange.Freight;
import com.magicsoft.share.bean.exchange.GoodsSubmit;
import com.magicsoft.share.bean.exchange.ShopCartGoods;
import com.magicsoft.share.customview.SwipeItemLayout;
import com.magicsoft.share.customview.alertview.AlertView;
import com.magicsoft.share.customview.alertview.OnItemClickListener;
import com.magicsoft.share.presenter.exchange.ShopCartPresenter;
import com.magicsoft.share.utils.DensityUtils;
import com.magicsoft.share.utils.ToastUtils;
import com.magicsoft.share.view.exchange.IShopCartView;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;
import com.yanzhenjie.recyclerview.swipe.widget.DefaultItemDecoration;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * A simple {@link Fragment} subclass.
 */
public class ShopCartFragment extends BaseFragment<IShopCartView, ShopCartPresenter> implements IShopCartView {


    @BindView(R.id.view_top)
    View viewTop;
    @BindView(R.id.ibtn_left)
    ImageButton ibtnLeft;
    @BindView(R.id.tv_left)
    TextView tvLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.ibtn_right)
    ImageButton ibtnRight;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.recyclerView)
    SwipeMenuRecyclerView recyclerView;
    @BindView(R.id.checkbox)
    CheckBox checkbox;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.btn_buy)
    Button btnBuy;


    private int pageNum = 1;
    private int pageSize = 10;
    private boolean isRefresh = true;

    private ShopCartAdapter shopCartAdapter;

    private List<ShopCartGoods.ListBean> data;
    private ArrayList<GoodsSubmit> goodsSubmits;
    private ArrayList<CheckStockValid> checkStockValids;
    private TextView freightText;
    private String ids;
    private AlertView alertView;
    private ArrayList<Integer> mPositons;


    public ShopCartFragment() {
        // Required empty public constructor
    }


    @Override
    public int getLayoutId() {
        return R.layout.fragment_shop_cart;
    }

    @Override
    public ShopCartPresenter initPresenter() {
        return new ShopCartPresenter();
    }

    @Override
    protected void initData() {

    }

    @Override
    public void initView() {
        tvTitle.setText("购物车");
        tvRight.setText("删除");

        ibtnLeft.setVisibility(View.INVISIBLE);
        initRV();
        checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                int money = shopCartAdapter.setCheckAll();
                 if(money<100){
                     tvPrice.setText((money+5) + "");
                 }else if(money==0){
                     tvPrice.setText(0 + "");
                 }{
                     tvPrice.setText(money + "");
                 }

            }
        });
        initDialog();

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        checkbox.setChecked(false);
        tvPrice.setText("0");
    }

    @Override
    protected void requestData() {
        mPresenter.shopCartGoods(pageNum, pageSize);
        mPresenter.freight();
    }

    @Override
    public void shopCartGoodsSuccess(ShopCartGoods data) {
        if (isRefresh) {
            shopCartAdapter.setNewData(data.getList());
        } else {
            shopCartAdapter.addData(data.getList());
        }

        if (pageNum < data.getPages()) {
            recyclerView.loadMoreFinish(false, true);
        } else if (pageNum == data.getPages()) {
            recyclerView.loadMoreFinish(false, false);
        } else {
            recyclerView.loadMoreFinish(true, false);
        }
        if(shopCartAdapter.getData().size()==0){
            Log.e("detel","df"+(shopCartAdapter.getItemCount()-1));
            recyclerView.setBackground(getResources().getDrawable(R.drawable.icon_nodata));
            tvPrice.setText("0");
        }else {
            recyclerView.setBackgroundColor(getResources().getColor(R.color.white));
        }

    }

    @Override
    public void shopCartGoodsFail() {
        if (isRefresh) {
            recyclerView.loadMoreFinish(true, false);
        } else {
            recyclerView.loadMoreFinish(false, false);
        }
    }

    @Override
    public void deleteGoodsSuccess(List<Integer> position) {
        List<ShopCartGoods.ListBean> data = shopCartAdapter.getData();
        for (int i = data.size() - 1; i >= 0; i--) {
            for (int j = 0; j < position.size(); j++) {
                if (i == position.get(j)) {
                    shopCartAdapter.remove(i);
                }
            }

        }
        if(shopCartAdapter.getData().size()==0){
            Log.e("detel","df"+(shopCartAdapter.getItemCount()-1));
            recyclerView.setBackground(getResources().getDrawable(R.drawable.icon_nodata));
            tvPrice.setText("0");
        }else {
            recyclerView.setBackgroundColor(getResources().getColor(R.color.white));
        }
    }

    @Override
    public void goodsIsValidSuccess() {

        Intent intent = new Intent(getContext(), SettlementActivity.class);
        String goodsStr = new Gson().toJson(goodsSubmits);
        intent.putExtra("goodsStr", goodsStr);
        intent.putExtra("isDirect", 0);
        intent.putExtra("orderAmount", Integer.valueOf(tvPrice.getText().toString()));
        intent.putExtra("GoodsList", goodsSubmits);

        startActivity(intent);
    }

    @Override
    public void goodsIsValidFail() {
        requestData();
    }

    @Override
    public void freightSuccess(Freight freight) {
        freightText.setText("订单金额满" + freight.getFreight_condition() + "金币免运费，未满运费5金币");
    }


    @OnClick({R.id.tv_right, R.id.btn_buy})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_buy:
                // startActivity(new Intent(this, SettlementActivity.class));
                buy();
                break;

            case R.id.tv_right:
                deleteAll();
                break;
            default:
                break;
        }
    }

    private void deleteAll() {
        mPositons = new ArrayList<>();
        ids = "";
        data = shopCartAdapter.getData();

        for (int i = 0; i < data.size(); i++) {
            if (data.get(i).getChoice() == 1) {
                mPositons.add(i);
                ids = ids + data.get(i).getGoodsId() + ",";
                Log.d("lyf", "deleteid: " + ids);
            }
        }
        if (mPositons.size() > 0) {
            Log.d("lyf", "deleteGoodsSuccess: " + shopCartAdapter.getData().size());
           alertView.show();
        }
    }


    private void buy() {

        goodsSubmits = new ArrayList<>();
        checkStockValids=new ArrayList<>();
        data = shopCartAdapter.getData();
        for (int i = 0; i < data.size(); i++) {
            if (data.get(i).getChoice() == 1) {


                checkStockValids.add(new CheckStockValid(data.get(i).getGoodsId(),data.get(i).getGoodsNum()));
                goodsSubmits.add(new GoodsSubmit(data.get(i).getGoodsId(), data.get(i).getGoodsName(), data.get(i).getGoodsImg(), data.get(i).getPrice(), data.get(i).getGoodsNum()));

            }
        }
        if (checkStockValids.size()==0) {
            ToastUtils.showToast(getContext(), "请选择商品");
        } else {


            mPresenter.goodsIsValid(new Gson().toJson(checkStockValids));
        }
    }


    private void initRV() {
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.addItemDecoration(new DefaultItemDecoration(getResources().getColor(R.color.bg), 0, DensityUtils.dp2px(getContext(), 0.8f), BaseQuickAdapter.FOOTER_VIEW));

        recyclerView.addOnItemTouchListener(new SwipeItemLayout.OnSwipeItemTouchListener(getContext()));


        shopCartAdapter = new ShopCartAdapter(R.layout.item_shop_cart);
        shopCartAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.delete) {
                    ArrayList<Integer> integers = new ArrayList<>();
                    integers.add(position);
                    mPresenter.deleteGoods(shopCartAdapter.getItem(position).getGoodsId() + "", integers);
                    int money = shopCartAdapter.setCheck(position);
                    if(money<100){
                        tvPrice.setText((money+5) + "");
                    }else {
                        tvPrice.setText(money + "");
                    }

                } else if (view.getId() == R.id.checkbox) {
                    int money = shopCartAdapter.setCheck(position);
                    if(money<100){
                        tvPrice.setText((money+5) + "");
                    }else {
                        tvPrice.setText(money + "");
                    }
                }
            }
        });
        View inflate = LayoutInflater.from(getContext()).inflate(R.layout.item_shop_cart_bottom, recyclerView, false);
        freightText = ((TextView) inflate.findViewById(R.id.textView));

        shopCartAdapter.addFooterView(inflate);
        recyclerView.setAdapter(shopCartAdapter);


    }


    private void initDialog() {
        alertView = new AlertView.Builder().setContext(getContext()).setTitle("是否删除？").setStyle(AlertView.Style.Alert).setCancelText("否").setOthers(new String[]{"是"}).setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {

                if (position == -1) {
                    alertView.dismiss();

                } else {
                    alertView.dismiss();
                    mPresenter.deleteGoods(ids, mPositons);

                }
            }
        }).build();
    }

}
